﻿using BSChuangXu.API.Read.Appicant.Commend.UserCommand;
using BSChuangXu.Domain.User;
using BSChuangXu.ErrorCode;
using BSChuangXu.Infrastructure.Interface;
using MediatR;

namespace BSChuangXu.API.Read.Appicant.CommendHandel.UserCommandHandler
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<UserModel>>
    {
        private readonly IBaseRepository<UserModel> userRepos;

        public LoginCommandHandler(IBaseRepository<UserModel> userRepos)
        {
            this.userRepos = userRepos;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIResult<UserModel>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserModel> result = new APIResult<UserModel>();

            var login = userRepos.GetAll().Result.FirstOrDefault(x => x.UserName == request.UserName 
            && x.Password == request.Password);
            if (login == null)
            {
                result.Code = APIEnum.登录失败密码或用户名错误;
                result.Msg = APIEnum.登录失败密码或用户名错误.ToString();
            }
            else
            {
                result.Code = APIEnum.登录成功;
                result.Msg = APIEnum.登录成功.ToString();
                result.data = login;
            }

            return Task.FromResult(result);
        }
    }
}
